// packageA/pages/addEmployee/addEmployee.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    from: {
      name: '',
      position: '',
      phone: '',
      synopsis: '',
      date: '',
      avater: ''
    },
    loading: false,
    id: ''
  },
  deleteImg(e){
    this.setData({ fileList: [] });
  },
  afterRead(event){
    let oldData = []
    let newData = oldData.concat(event.detail.file)
    this.setData({ fileList: newData });
  },
  phoneChange(e){
    this.setData({['from.phone']: e.detail})
  },
  nameChange(e){
    this.setData({['from.name']: e.detail})
  },
  positionChange(e){
    this.setData({['from.position']: e.detail})
  },
  synopsisChange(e){
    this.setData({['from.synopsis']: e.detail})
  },
  sumbit(){
    if (this.data.fileList.length == 0) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
      return
    }
    if(!this.data.from.name){
      wx.showToast({ title: '请输入名称', icon: 'none' });
      return
    }
    if(!this.data.from.position){
      wx.showToast({ title: '请输入职位', icon: 'none' });
      return
    }
    if(!this.data.from.phone){
      wx.showToast({ title: '请输入电话', icon: 'none' });
      return
    }
    this.uploadToCloud()
  },
  uploadToCloud(){
    this.setData({
      loading: true
    })
    let that = this
    wx.cloud.callFunction({
      name: 'getOpenid',
      success(res){
        console.log(that.data.fileList);
        let openid = res.result.openid
        let fileList = that.data.fileList
        let date = Date.now()
        if(that.data.from.avater != fileList[0].url){
          let name = openid + '.' + date + '.png'
          wx.cloud.uploadFile({
            cloudPath: name,
            filePath: fileList[0].url
          })
          .then(res => {
            that.setData({['from.avater']: res.fileID})
            if(!that.data.id){
              that.add(date)
            }else {
              that.edit()
            }
          }).catch(e => {
            console.log(e);
            wx.showToast({ title: '上传失败', icon: 'none' });
            that.setData({
              loading: false
            })
          });
        }else {
          that.edit()
        }
       
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id){
      this.setData({id: options.id})
    }
  },
  add(date){
    let that = this
    that.setData({['from.date']: that.timestampToTime(date)})
    db.collection('employeeInfo').add({data: that.data.from}).then(d=>{
      wx.showToast({ title: '成功', icon: 'none' });
      setTimeout(()=>{
        const pages = getCurrentPages(); //获取页面栈
        const beforePage = pages[pages.length - 2]; //前一个页面
        beforePage.refresh();
        wx.navigateBack({
          delta: 1,
          success:(res)=>{
            that.setData({
              loading: false
            })
          }
        })
      },500)
    })
  },
  edit(){
    let that = this
    db.collection('employeeInfo').doc(that.data.id).update({data: that.data.from}).then(d=>{
      wx.showToast({ title: '成功', icon: 'none' });
      setTimeout(()=>{
        const pages = getCurrentPages(); //获取页面栈
        const beforePage = pages[pages.length - 2]; //前一个页面
        beforePage.refresh();
        wx.navigateBack({
          delta: 1,
          success:(res)=>{
            that.setData({
              loading: false
            })
          }
        })
      },500)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if(this.data.id){
      this.getList()
    }
  },
  timestampToTime(timestamp) {
    timestamp = timestamp ? timestamp : null;
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  },
  getList(){
    db.collection('employeeInfo').doc(this.data.id).get().then(res=>{
      console.log(res);
      let data = {
        name: res.data.name,
        position: res.data.position,
        phone: res.data.phone,
        synopsis: res.data.synopsis,
        date: res.data.date,
        avater: res.data.avater
      }
      let fileList = [{url: res.data.avater}]
      this.setData({from: data, fileList: fileList})
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})